<template>
  <el-card class="box-card">
    <el-form ref="queryForm" :model="query" :inline="true">
      <el-form-item label="">
        <el-input v-model.trim="query.conditions.menuName" placeholder="菜单名称" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item label="标签名称">
        <el-select style="width: 100px" v-model="query.conditions.wxTagId" placeholder="全部">
          <el-option
            v-for="item in signList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态">
        <el-select style="width: 100px" v-model="query.conditions.publishState" placeholder="全部">
          <el-option label="未发布" :value="0"></el-option>
          <el-option label="已发布" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button v-has-permi="['/wx/menu/postAddWxMenu']" type="primary" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <el-table v-loading="listLoading" :data="dataList" border stripe>
        <el-table-column prop="name" label="菜单名称" align="center" show-overflow-tooltip width="160" />
        <el-table-column label="关联标签" align="center" prop="wxTagName" />
        <el-table-column label="发布状态" align="center" prop="createTime">
          <template slot-scope="{row}">
            <span v-if="row.publishState===1">发布成功</span>
            <span v-else-if="row.publishState===2">发布失败</span>
            <span v-else>未发布</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" prop="createTime">
          <template slot-scope="{row}">
            <span>{{ row.publishTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-has-permi="['/wx/menu/pushCustomMenu']" type="text" @click="handleState(row)">
              <span v-if="row.publishState===1">取消发布</span>
              <span v-else>发布</span>
            </el-button>
            <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/postUpdateWxMenu']"  type="text" @click="handleAdd(row)">编辑</el-button>
            <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/getCustomMenuOneAndTow/*']"  type="text" @click="handleMenu(row.id)">设置菜单</el-button>
            <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/postDelWxMenu']" type="text" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 添加或修改菜单 -->
    <el-dialog :title="(formModel.id?'编辑':'新增')+'菜单'" :visible.sync="formVisible" width="760px" append-to-body>
      <el-form ref="formModel" :model="formModel" :rules="formModelRules" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="12" :offset="0">
            <el-form-item label="菜单名称:" prop="name">
              <el-input v-model.trim="formModel.name" clearable placeholder="请输入菜单名称" maxlength="12" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="关联标签:" prop="wxTagId">
              <el-select v-model="formModel.wxTagId" placeholder="默认标签">
                <el-option
                  v-for="item in signList"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </el-card>
</template>

<script>
import { menuListPage, editMenu, addMenu, deleteMenu, pushCustomMenu, pushCustomMenuCancel } from '@/api/wechatService/menu'
import { signListPage, getWxTagList } from '@/api/wechatService/sign'

export default {
  name: "menu-manage",
  data () {
    return {
      total: 0,
      // 列表数据
      query: {
        pageNum: 1,
        pageSize: 10,
        conditions: {}
      },
      dataList: [],
      listLoading: false,
      // 新增/编辑用户
      formVisible: false,
      submitLoading: false,
      signList: [],
      signFilterList: [],
      formModel: {},
      formModelRules: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        wxTagId: [
          { required: true, message: "关联标签不能为空", trigger: "blur" }
        ]
      },
    }
  },
  mounted () {
    this.handleQuery()
    this.querySignList()
  },
  methods: {
    // 查询标签list
    querySignList() {
      signListPage({
        pageSize: 100,
        pageNum: 1,
        conditions: {
          enabledState: 1
        }
      }).then(res => {
        this.signList = res.data.records
      })
      getWxTagList().then(res => {
        this.signFilterList = res.data
      })
    },
    // 列表
    handleQuery () {
      this.listLoading = true
      let params = {...this.query}
      menuListPage(params).then(res => {
        this.dataList = res.data?res.data.records: []
        this.dataList.forEach(it => {
          if(it.children.length>0) {
            it.children.forEach(it2 => {
              it2.tagName = it.tagName
              it2.faButtonSequence = it.buttonSequence
            })
          }
        })
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    // 重置搜索条件
    resetQuery () {
      this.query = {
        pageNum: 1,
        pageSize: 10,
        conditions: {}
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增/编辑弹窗
    handleAdd(row) {
      this.reset()
      if (row) {
        const { id, name, wxTagId } = row
        this.formModel = { id, name, wxTagId }
      }
      this.formVisible = !this.formVisible
    },
    // 设置菜单
    handleMenu (id) {
      this.$router.push(`/wechatServicer/menuContr/menu/${id}`)
    },
    // 发布/取消发布
    handleState({id,publishState}) {
      this.$confirm(`请确认是否要${publishState===1?'发布':'取消发布'}该菜单?`, { type: 'warning' }).then(async () => {
        try {
          if (publishState===1) {
            await pushCustomMenuCancel({ id })
            this.$message.success('取消成功')
          } else {
            await pushCustomMenu({ id })
            this.$message.success('发布成功')
          }
          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 删除
    handleDelete (id) {
      this.$confirm(`请确认是否要删除该菜单?`, { type: 'warning' }).then(() => {
        let params = {
          id: id
        }
        deleteMenu(params).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      })
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          let params = {...this.formModel}
          try {
            if (params.id) {
              await editMenu(params)
              this.$message.success('修改成功')
            } else {
              await addMenu(params)
              this.$message.success('新增成功')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {}
      this.resetForm("formModel")
    },
  },
}
</script>

<style scoped>

</style>
